package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

// User 用户结构体，client有相同结构体，启动时需删掉一个
type User struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Age      int    `json:"age"`
	CreateAt string `json:"create_at"`
}

// Response 响应结构体
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// HTTP客户端
type HTTPClient struct {
	baseURL string
	client  *http.Client
}

// 创建新的HTTP客户端
func NewHTTPClient(baseURL string) *HTTPClient {
	return &HTTPClient{
		baseURL: baseURL,
		client: &http.Client{
			Timeout: 10 * time.Second,
		},
	}
}

// 发送GET请求
func (c *HTTPClient) Get(path string) (*Response, error) {
	resp, err := c.client.Get(c.baseURL + path)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return c.parseResponse(resp)
}

// 发送POST请求
func (c *HTTPClient) Post(path string, data interface{}) (*Response, error) {
	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	resp, err := c.client.Post(c.baseURL+path, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return c.parseResponse(resp)
}

// 发送PUT请求
func (c *HTTPClient) Put(path string, data interface{}) (*Response, error) {
	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("PUT", c.baseURL+path, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return c.parseResponse(resp)
}

// 发送DELETE请求
func (c *HTTPClient) Delete(path string) (*Response, error) {
	req, err := http.NewRequest("DELETE", c.baseURL+path, nil)
	if err != nil {
		return nil, err
	}

	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return c.parseResponse(resp)
}

// 解析响应
func (c *HTTPClient) parseResponse(resp *http.Response) (*Response, error) {
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var response Response
	err = json.Unmarshal(body, &response)
	if err != nil {
		return nil, err
	}

	return &response, nil
}

// 演示各种HTTP请求
func main() {
	client := NewHTTPClient("http://localhost:8080")

	fmt.Println("=== HTTP客户端演示 ===\n")

	// 1. 健康检查
	fmt.Println("1. 健康检查:")
	healthResp, err := client.Get("/health")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", healthResp)
	}
	fmt.Println()

	// 2. 获取所有用户
	fmt.Println("2. 获取所有用户:")
	usersResp, err := client.Get("/api/users")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", usersResp)
	}
	fmt.Println()

	// 3. 创建新用户
	fmt.Println("3. 创建新用户:")
	newUser := User{
		Name:  "王五",
		Email: "wangwu@example.com",
		Age:   28,
	}
	createResp, err := client.Post("/api/users", newUser)
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", createResp)
	}
	fmt.Println()

	// 4. 获取指定用户
	fmt.Println("4. 获取用户ID=1:")
	userResp, err := client.Get("/api/users/1")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", userResp)
	}
	fmt.Println()

	// 5. 更新用户
	fmt.Println("5. 更新用户ID=1:")
	updateUser := User{
		Name:  "张三(已更新)",
		Email: "zhangsan_updated@example.com",
		Age:   26,
	}
	updateResp, err := client.Put("/api/users/1", updateUser)
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", updateResp)
	}
	fmt.Println()

	// 6. 删除用户
	fmt.Println("6. 删除用户ID=2:")
	deleteResp, err := client.Delete("/api/users/2")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", deleteResp)
	}
	fmt.Println()

	// 7. 再次获取所有用户
	fmt.Println("7. 删除后的用户列表:")
	finalUsersResp, err := client.Get("/api/users")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Printf("响应: %+v\n", finalUsersResp)
	}
	fmt.Println()

	fmt.Println("=== 演示完成 ===")
}
